package com.tehui.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;

import com.ali.auth.third.core.model.Session;
import com.ali.auth.third.ui.context.CallbackContext;
import com.alibaba.baichuan.android.trade.adapter.login.AlibcLogin;
import com.alibaba.baichuan.android.trade.callback.AlibcLoginCallback;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.tehui.R;
import com.tehui.global.LoginMode;
import com.tehui.utils.tools.MD5Encoder;
import com.tehui.utils.tools.PrefUtils;
import com.tehui.utils.ui.UiUtils;
import com.tencent.connect.UserInfo;
import com.tencent.connect.common.Constants;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

import static com.tehui.app.MyApplication.IS_TAOKE;
import static com.tehui.app.MyApplication.WX_APPID;
import static com.tehui.app.MyApplication.WX_APP_SECRET;

//登录页面,无短信注册
public class LoginActivity extends BaseActivity {

    @BindView(R.id.etNum)
    EditText    etNum;
    @BindView(R.id.etPassword)
    EditText    etPassword;
    @BindView(R.id.register)
    Button      register;
    @BindView(R.id.forget)
    Button      forget;
    @BindView(R.id.wechat)
    ImageButton wechat;
    @BindView(R.id.tecent)
    ImageButton tecent;
    @BindView(R.id.taobao)
    ImageButton taobao;
    @BindView(R.id.imageView)
    ImageView   ivLogo;

    private static Tencent          mTencent;
    private        UserInfo         userInfo;
    private        String           encode;
    private        IWXAPI           api;
    private        ReceiveBroadCast receiveBroadCast;

    @Override
    public void initActivityData() {
        super.initActivityData();
        mTencent = Tencent.createInstance("1106154936", this);
        initLogo();
    }

    private void initLogo() {
        if (IS_TAOKE) {
            ivLogo.setImageResource(R.drawable.logo_big);
        } else {
            ivLogo.setImageResource(R.drawable.logo_big1);
        }
    }

    @Override
    public void initViewListener() {
        super.initViewListener();
        goBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setResult(1);
                finish();
            }
        });
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_login;
    }

    @Override
    protected void onResume() {
        super.onResume();
        receiveBroadCast = new ReceiveBroadCast();
        IntentFilter intentFliter = new IntentFilter();
        intentFliter.addAction("authlogin");
        registerReceiver(receiveBroadCast, intentFliter);
    }

    @OnClick({R.id.wechat, R.id.tecent, R.id.taobao, R.id.login})
    public void onClick(View view) {
        if (!UiUtils.isNetworkAvailable()) {
            UiUtils.toast("网络出问题了,请稍候重试!");
            return;
        }
        switch (view.getId()) {
            case R.id.wechat:
                loginWeChat();
                break;
            case R.id.tecent:
                loginTencent();
                break;
            case R.id.taobao:
                final AlibcLogin alibcLogin = AlibcLogin.getInstance();
                alibcLogin.showLogin(LoginActivity.this, new AlibcLoginCallback() {
                    @Override
                    public void onFailure(int i, String s) {
                    }

                    @Override
                    public void onSuccess() {
                        //MobclickAgent.onEvent(UiUtils.getContext(), "login_taobao");
                        PrefUtils.setBoolean("isLogin", true);
                        Session session = alibcLogin.getSession();
                        try {
                            String openId = MD5Encoder.encode(session.openId);

                            String nick = session.nick;
                            String avatarUrl = session.avatarUrl;

                            PrefUtils.setString("openId", openId);
                            PrefUtils.setString("nick", nick);
                            PrefUtils.setString("avatarUrl", avatarUrl);

                            PrefUtils.setInt("loginMode", LoginMode.LOGIN_TAOBAO);
                            LoginActivity.this.setResult(0);
                            finish();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
                break;
            case R.id.login:
                String userName = PrefUtils.getString("userName", "");
                String password = PrefUtils.getString("password", "");
                String userPhone = etNum.getText().toString().trim();
                String userPassword = etPassword.getText().toString().trim();
                if (TextUtils.isEmpty(userPhone)) {
                    UiUtils.toast("手机号不能为空!");
                    return;
                }
                if (TextUtils.isEmpty(userPassword)) {
                    UiUtils.toast("密码不能为空!");
                    return;
                }
                try {
                    encode = MD5Encoder.encode(userPassword);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (userName.equals(userPhone) && encode.equals(password)) {
                    UiUtils.toast("登录成功");
                    PrefUtils.setBoolean("isLogin", true);
                    this.setResult(0);
                    finish();
                } else {
                    UiUtils.toast("用户名或密码错误");
                }
                break;
        }
    }

    //微信登录
    private void loginWeChat() {
        if (api == null) {
            api = WXAPIFactory.createWXAPI(this, WX_APPID, true);
        } else if (!api.isWXAppInstalled()) {
            UiUtils.toast("您未安装微信,请先安装微信!");
            return;
        }
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wx_login_taile";
        api.sendReq(req);
    }

    public void loginTencent() {
        mTencent.login(this, "all", loginListener);
    }

    //QQ
    private void updateUserInfo() {
        IUiListener iUiListener = new IUiListener() {
            @Override
            public void onComplete(Object o) {
                JSONObject json = (JSONObject) o;
                try {
                    String nickname = json.getString("nickname");
                    String figureurl = json.getString("figureurl_qq_2");
                    String city = json.getString("city");
                    String sex = json.getString("gender");

                    PrefUtils.setString("nick", nickname);
                    PrefUtils.setString("avatarUrl", figureurl);
                    PrefUtils.setString("sex", sex);
                    PrefUtils.setString("city", city);
                    finish();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(UiError uiError) {

            }

            @Override
            public void onCancel() {

            }
        };

        userInfo = new UserInfo(this, mTencent.getQQToken());
        userInfo.getUserInfo(iUiListener);
    }

    //QQ
    IUiListener loginListener = new BaseUiListener() {
        @Override
        protected void doComplete(JSONObject values) {
            initOpenidAndToken(values);
            updateUserInfo();
        }
    };


    //qq登录
    private class BaseUiListener implements IUiListener {
        @Override
        public void onComplete(Object response) {
            if (null == response) {
                UiUtils.toast("登录失败");
                return;
            }
            JSONObject jsonResponse = (JSONObject) response;
            if (null != jsonResponse && jsonResponse.length() == 0) {
                UiUtils.toast("登录失败");
                return;
            }
            doComplete((JSONObject) response);

            //MobclickAgent.onEvent(UiUtils.getContext(), "login_tencent");

            PrefUtils.setBoolean("isLogin", true);
            PrefUtils.setInt("loginMode", LoginMode.LOGIN_TENCENT);
            LoginActivity.this.setResult(0);
        }

        protected void doComplete(JSONObject values) {

        }

        @Override
        public void onError(UiError e) {
        }

        @Override
        public void onCancel() {
        }
    }

    //QQ
    public static void initOpenidAndToken(JSONObject jsonObject) {
        try {
            String token = jsonObject.getString(Constants.PARAM_ACCESS_TOKEN);
            String expires = jsonObject.getString(Constants.PARAM_EXPIRES_IN);
            String openId = jsonObject.getString(Constants.PARAM_OPEN_ID);
            String userOpenId = MD5Encoder.encode(openId);
            PrefUtils.setString("openId", userOpenId);

            if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(expires) && !TextUtils.isEmpty(openId)) {
                mTencent.setAccessToken(token, expires);
                mTencent.setOpenId(openId);
            }
        } catch (Exception e) {
        }
    }

    //获取微信AccessToken
    public void getAccessToken() {
        String wxCode = PrefUtils.getString("WXCode", "");
        String path = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WX_APPID + "&secret=" +
                WX_APP_SECRET + "&code=" + wxCode + "&grant_type=authorization_code";

        OkGo.get(path).tag(this)
                //请求的 tag,
                .cacheKey("cacheKey").cacheMode(CacheMode.DEFAULT).execute(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {

                try {
                    JSONObject jsonObject = new JSONObject(s);
                    String openid1 = jsonObject.getString("openid");
                    String openid = MD5Encoder.encode(openid1);
                    String access_token = jsonObject.getString("access_token").toString();
                    PrefUtils.setString("openId", openid);
                    getUserMesg(access_token, openid1);
                    LoginActivity.this.setResult(0);
                    //MobclickAgent.onEvent(UiUtils.getContext(), "login_wechat");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
            }
        });
    }

    /**
     * 获取微信的个人信息
     * @param access_token
     * @param openid
     */
    private void getUserMesg(final String access_token, final String openid) {
        String path = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" +
                openid;
        OkGo.get(path).tag(this).cacheKey("cacheKey").cacheMode(CacheMode.DEFAULT).execute(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                try {
                    JSONObject jsonObject = new JSONObject(s);

                    String nickname = jsonObject.getString("nickname");
                    String headimgurl = jsonObject.getString("headimgurl");
                    String city = jsonObject.getString("city");
                    String sex = jsonObject.getString("sex");

                    PrefUtils.setString("sex", sex);
                    PrefUtils.setString("city", city);
                    PrefUtils.setString("nick", nickname);
                    PrefUtils.setString("avatarUrl", headimgurl);

                    PrefUtils.setInt("loginMode", LoginMode.LOGIN_WECHAT);
                    PrefUtils.setBoolean("isLogin", true);

                    finish();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        CallbackContext.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.REQUEST_LOGIN || requestCode == Constants.REQUEST_APPBAR) {
            Tencent.onActivityResultData(requestCode, resultCode, data, loginListener);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onBackPressed() {
        this.setResult(1);
        super.onBackPressed();
    }

    public class ReceiveBroadCast extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            getAccessToken();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        try {
            unregisterReceiver(receiveBroadCast);
        } catch (Exception e) {
        }
        super.onDestroy();
    }
}


